package com.bjut.vendormgrsys.web.rest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@RestController
public class SysFileApiController implements SysFileApi {
    private static final Logger log = LoggerFactory.getLogger(SysFileApiController.class);

    @Override
    public ResponseEntity<InputStreamResource> download(@Valid String url) throws IOException {
        FileSystemResource file = new FileSystemResource(url);
        String name  = file.getFilename();
        if(!file.exists()){
            return null;
        }
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
//        headers.add("charset", "UTF-8");
//        headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getFilename()));

        //解决中文乱码
        headers.add("Content-Disposition","attachment; fileName="+new String(name.getBytes("utf-8"),"ISO-8859-1"));
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");


        return ResponseEntity
                .ok()
                .headers(headers)
                .contentLength(file.contentLength())
                // .contentType(MediaType.parseMediaType("application/octet-stream"))
                .contentType(MediaType.parseMediaType("application/x-msdownload"))
                .body(new InputStreamResource(file.getInputStream()));
    }

    @Override
    public void fileShow(HttpServletResponse response, @RequestParam String url) {

        File image = new File(url);
        FileInputStream inputStream = null;
        if(image.isFile()) {
            try {
                inputStream = new FileInputStream(image);
                int i = inputStream.available();
                byte [] bytes = new byte[i];
                inputStream.read(bytes);
                response.getOutputStream().write(bytes);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if(inputStream != null){
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } else {
            log.error("没有要显示的文件信息,url:  "+url);
        }
    }
}
